<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.info" placeholder="类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in typeOption" :key="key" :label="value" :value="key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleInit">
        初始化考勤
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="80" fixed>
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级" align="center" width="80" fixed>
        <template slot-scope="{row}">
          <span>{{ row.schoolClassInfo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学号" align="center" width="80" fixed>
        <template slot-scope="{row}">
          <span>{{ row.userInfo.number }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" width="80" fixed>
        <template slot-scope="{row}">
          <span>{{ row.userInfo.name }}</span>
        </template>
      </el-table-column>

      <el-table-column v-for="index in dateHeader" :key="index" :label="index" align="center">
        <el-table-column label="上午" align="center">
          <el-table-column v-for="indexTwo in ['0','1','2','3']" :key="indexTwo" :label="indexTwo" align="center">
            <template slot-scope="{row}">
              <el-tooltip class="item" effect="dark" :content="String(JSON.parse(row.info)[index][indexTwo].time)" placement="top-start">
                <span @click="cellClick(row, index, indexTwo, JSON.parse(row.info)[index][indexTwo])">{{ typeOption[JSON.parse(row.info)[index][indexTwo].type] }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="下午" align="center">
          <el-table-column v-for="indexTwo in ['4','5','6','7']" :key="indexTwo" :label="indexTwo" align="center">
            <template slot-scope="{row}">
              <el-tooltip class="item" effect="dark" :content="String(JSON.parse(row.info)[index][indexTwo].time)" placement="top-start">
                <span @click="cellClick(row, index, indexTwo, JSON.parse(row.info)[index][indexTwo])">{{ typeOption[JSON.parse(row.info)[index][indexTwo].type] }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table-column>
      <el-table-column label="考勤结果" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ isPassOption[row.is_pass] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考勤明细" align="center" width="80">
        <el-table-column label="正常" align="center" width="80">
          <template slot-scope="{row}">
            <span v-if="row.is_pass == 0" style="color: red">{{ zhengchangOption[row.is_pass] }}</span>
            <span v-else>{{ zhengchangOption[row.is_pass] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="请假" align="center" width="80">
          <template slot-scope="{row}">
            <span>{{ sumTime(row, 2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调课" align="center" width="80">
          <template slot-scope="{row}">
            <span>{{ sumTime(row, 3) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="迟到" align="center" width="80">
          <template slot-scope="{row}">
            <span>{{ sumTime(row, 4) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="早退" align="center" width="80">
          <template slot-scope="{row}">
            <span>{{ sumTime(row, 5) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="旷课" align="center" width="80">
          <template slot-scope="{row}">
            <span>{{ sumTime(row, 6) }}</span>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item label="姓名">
          <span>{{ temp.userName }}</span>
        </el-form-item>
        <el-form-item label="班级">
          <span>{{ temp.className }}</span>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="temp.type" prop="type" class="filter-item">
            <el-option v-for="(value,key) in typeOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间(分钟)">
          <el-input v-model="temp.time" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { timetableKaoqinInit, timetableKaoqinPage, timetableKaoqinUpdateInfo } from '@/api/course'
import waves from '@/directive/waves' // waves directive
import { notifySuccess, formatJson, listQueryFilter, myConfirmMessage, minuteToStr } from '@/utils/tool'

export default {
  name: 'KaoqinPage',
  components: { },
  directives: { waves },
  filters: {
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      restaurants: [],
      dateHeader: [],
      dateList: [],
      q: 0,
      state: '',
      timeout: null,
      listLoading: true,
      listQuery: { // 查询初始值
        page: 1,
        limit: 999,
        course_timetable_id: this.$route.query.id,
        info: ''
      },
      typeOption: {
        1: '√',
        2: 'Q',
        3: 'T',
        4: 'CH',
        5: 'K',
        6: 'Z'
      },
      isPassOption: {
        0: '不合格',
        1: '合格'
      },
      zhengchangOption: {
        0: 'X',
        1: '√'
      },
      temp: {
        userName: '',
        className: '',
        id: '',
        type: '1',
        time: '',
        index: '',
        indexTwo: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      rules: {

      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    cellClick(row, index, indexTwo, data) {
      this.temp.userName = row.userInfo.name
      this.temp.className = row.schoolClassInfo.name
      this.temp.type = data.type + ''
      this.temp.time = data.time
      this.temp.id = row.id
      this.temp.index = index
      this.temp.indexTwo = indexTwo
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    getList() {
      this.listLoading = true
      this.listQuery = listQueryFilter(this.listQuery)
      timetableKaoqinPage(this.listQuery).then(response => {
        this.list = response.data
        if (response.data.length > 0) {
          var c = JSON.parse(response.data[0]['info'])
          this.dateHeader = Object.keys(c)
        }
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleInit() {
      myConfirmMessage('是否初始化当前考勤信息?', this, () => {
        timetableKaoqinInit({ courseTimetableId: this.listQuery.course_timetable_id }).then(() => {
          this.getList()
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          timetableKaoqinUpdateInfo(tempData).then(() => {
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
            this.getList()
          })
        }
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'sort') {
        this.sortByID(order, prop)
      }
    },
    sortByID(order, prop) {
      if (order === 'ascending') {
        this.listQuery.querySort = '+' + prop
      } else {
        this.listQuery.querySort = '-' + prop
      }
      this.handleFilter()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['名称', '学号', '学校邮箱', '个人邮箱']
        const filterVal = ['name', 'number', 'school_email', 'self_email']
        const data = formatJson(this, filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '用户学生表'
        })
        this.downloadLoading = false
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.querySort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    sumTime: function(row, num) {
      var time = 0
      var rowInfo = Object.values(JSON.parse(row.info))
      rowInfo.forEach(function(info, index) {
        info.forEach(function(val, key) {
          if (num === parseInt(val.type)) {
            time = time + parseInt(val.time)
          }
        })
      })
      if (time === 0) {
        return ''
      } else {
        return minuteToStr(time)
      }
    }
  }
}
</script>
